
#include "server.h"
#include "monotonic.h"

#include <stdio.h>
#include <signal.h>
#include <sys/wait.h>
#include <time.h>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <stdarg.h>
#include <stdlib.h>

struct redisServer server;

/* Like serverLogRaw() but with printf-alike support. This is the function that
 * is used across the code. The raw version is only used in order to dump
 * the INFO output on crash. */
void _serverLog(int level, const char *fmt, ...) {
    va_list ap;
    char msg[LOG_MAX_LEN];

    va_start(ap, fmt);
    vsnprintf(msg, sizeof(msg), fmt, ap);
    va_end(ap);

    serverLogRaw(level,msg);
}

int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
    /* We need to do a few operations on clients asynchronously. */
    //clientsCron();

    serverLog(LL_NOTICE, "serverCron\n");

    return 1000/CONFIG_MIN_HZ;
}

void initServer(void){
    signal(SIGHUP, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);

    const char *clk_msg = monotonicInit();
    serverLog(LL_NOTICE, "monotonic clock: %s", clk_msg);

    server.el = aeCreateEventLoop(10);
    if (server.el == NULL) {
        serverLog(LL_WARNING,
            "Failed creating the event loop. Error message: '%s'",
            strerror(errno));
        exit(1);
    }

    if (aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL) == AE_ERR) {
        serverLog(LL_WARNING, "Can't create event loop timers.");
        exit(1);
    }
}

/* Low level logging. To use only for very big messages, otherwise
 * serverLog() is to prefer. */
void serverLogRaw(int level, const char *msg) {
    const int syslogLevelMap[] = { LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING };
    const char *c = ".-*#";
    FILE *fp;
    char buf[64];

    fp = stdout;
    if (!fp) return;
    fprintf(fp,"%s",msg);
    fflush(fp);
}

int main(int argc, char const *argv[])
{
    initServer();
    aeMain(server.el);
    return 0;
}
